package com.boxin.ims.modules.wechat.utils;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatApiToken;
import com.boxin.ims.modules.wechat.service.WeChatService;

public class TokenUtils {
	
	public final static long TIME_OUT = 7100;	// 超时为7200秒
	
	private static Map<String , WechatApiToken> tokenMap  = new HashMap<String, WechatApiToken>();
	
	@Autowired
	private static WeChatService weChatService;
	
	
	public static DefaultHttpClient httpclient;
	
	private static Map<Long,Map<String, String>> userMap = new HashMap<Long,Map<String, String>>();
	
	static {
		httpclient = new DefaultHttpClient();
		httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient); // 接受任何证书的浏览器客户端
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-6-21  下午5:17:43
	 * @function <p> 获取一个缓存的 Token </p>
	 * @param weChat
	 * @return
	 */
	public static String  getAPIToken(WeChat weChat){
		
		WechatApiToken  token = tokenMap.get(weChat.getAppId());
		
		if(isValiable(token)){
			System.out.println("当前Token可用未超时."+token.getToken());
			return token.getToken();
		}else{
			String strToken = getNewToken(weChat);
			return strToken;
		}	
	}
	
	public static Map<Long, Map<String, String>> getUserMap() {
		return userMap;
	}
	
	/**
	 * 通过userId  获得token
	 * @param userId
	 * @return
	 */
	public static String  getAPITokenByuser(Long userId){
		
		WeChat weChat= weChatService.getWeChatByUserId(userId);
		WechatApiToken  token = tokenMap.get(weChat.getAppId());
		return token.getToken();
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-9-10  下午4:28:52
	 * @function <p> 删除缓存中的Token </p>
	 * @param weChat
	 */
	public static void removeAPIToken(WeChat weChat){
		tokenMap.remove(weChat.getAppId());
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-7-3  上午9:34:35
	 * @function <p> 根据appid,secret查找 accessToken </p>
	 * @param appId
	 * @param secret
	 * @return
	 */
	public static String getAPIToken(String appId,String secret){
		
		WechatApiToken  token = tokenMap.get(appId);
		if(isValiable(token)){
			System.out.println("当前Token可用未超时.");
			return token.getToken();
		}else{
			WeChat weChat = new WeChat();
			weChat.setAppId(appId);
			weChat.setAppSecret(secret);
			String strToken = getNewToken(weChat);
			return strToken;
		}
		
		
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-6-21  下午5:17:14
	 * @function <p>当前的Token是否可用是否超时  </p>
	 * @param token
	 * @return
	 */
	private static boolean isValiable(WechatApiToken token){
		if(token == null) return false;
		long now = System.currentTimeMillis();
		long diff = now - token.getStart() ;
		if(diff/1000 > TIME_OUT){
			return false;
		}
		return true;
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-6-21  下午5:16:59
	 * @function <p> 重新获取一个新Token </p>
	 * @param weChat
	 * @return
	 */
	private static String getNewToken(WeChat weChat){
		try {
			//String accessToken= WechatMenuUtils.getAccessToken(weChat.getAppId(), weChat.getAppSecret());
			
			
			HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + weChat.getAppId() + "&secret=" + weChat.getAppSecret());
			HttpResponse response = httpclient.execute(get);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			String accessToken  = object.getString("access_token");
			
			
			
			
			WechatApiToken  apiToken = new WechatApiToken();
			apiToken.setAppId(weChat.getAppId());
			apiToken.setStart(System.currentTimeMillis());
			apiToken.setSecretKey(weChat.getAppSecret());
			apiToken.setToken(accessToken);
			tokenMap.put(weChat.getAppId(),apiToken);
			System.out.println("生成新Token:"+accessToken);
			return accessToken;
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
		return null;
	}
	
	
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-6-21  下午5:25:36
	 * @function <p>  </p>
	 * @param args
	 */
	public static void main(String[] args) {
		
		String appId = "wxc5822a0e936601fd";
		String appSecret = "81bee9b56756d769eab609ced7f635fa";
		
		WeChat weChat = new WeChat();
		weChat.setId(33L);
		weChat.setAppId(appId);
		weChat.setAppSecret(appSecret);
		
		
		
		
		String mediaId = "6027317791923634176";
		String token = getAPIToken(weChat);
		
		String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+token+"&media_id="+mediaId;
		System.out.println(url);
		
		
		
//		for(int i= 0;i<10;i++){
//			try {
//				Thread.sleep(1000);
//				System.out.println("第"+(i+1)+"个Token:"+token);
//				
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
		
	}

}
